﻿using System;
using System.Text;
using System.Web;
using System.Web.UI;

using Cognifide.PowerShell.Shell.Host;
using Cognifide.PowerShell.Shell.Settings;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;

namespace Cognifide.PowerShell.Console.Layouts
{
    public partial class PowerShellResults : Page
    {
        private string itemId;
        private string itemDb;
        private string scriptId;
        private string scriptDb;

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            itemId = HttpContext.Current.Request.Params["id"];
            itemDb = HttpContext.Current.Request.Params["db"];
            scriptId = HttpContext.Current.Request.Params["scriptId"];
            scriptDb = HttpContext.Current.Request.Params["scriptDb"];

            if (String.IsNullOrEmpty(itemDb))
            {
                itemDb = "master";
            }

            Item scriptItem = Factory.GetDatabase(scriptDb).GetItem(new ID(scriptId));

            string script = String.Format("Set-HostProperty -HostWidth 80\n{0}\n", PsConsoleSettings.Instance.PreScript);

            if (!string.IsNullOrEmpty(itemId) && !string.IsNullOrEmpty(itemDb))
            {
                Item item = Factory.GetDatabase(itemDb).GetItem(new ID(itemId));
                script += String.Format(
                    "cd \"{0}:{1}\"\n", item.Database.Name, item.Paths.Path.Replace("/", "\\").Substring(9));
            }

            script += scriptItem != null ? (scriptItem["Script"] as string) : "Write-Host 'Script item not found!'";

            ExecutionControl.Script = script;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ExecutionControl.Execute();
        }

    }
}